﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.Threading;
using Entities;

namespace Logic
{
	public class FilmAffinityScrapper
	{
		private WebClient Web = new WebClient();

		public FilmAffinityScrapper()
		{
		}

		public Movie GetMovieInfoFromURL(string url)
		{
			Movie Movie = new Movie();
			try
			{
				StreamReader stream = new StreamReader(Web.OpenRead(url));

				string html = stream.ReadToEnd();

				stream.Close();
				stream.Dispose();

				Regex r2 = new Regex("http://pics\\.filmaffinity\\.com/(_?-?\\w*)*-large\\.jpg", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
				if (r2.IsMatch(html))
					Movie.Poster = r2.Matches(html)[0].Value; //Poster. No siempre funciona.
				else
					Movie.Poster = "http://hpneo.com/DoubleFeature/img/poster_default.jpg";

				HtmlAgilityPack.HtmlDocument HD = new HtmlAgilityPack.HtmlDocument();
				HD.LoadHtml(html);

				HtmlAgilityPack.HtmlNodeCollection NODES = HD.DocumentNode.SelectNodes("//table[@valign='baseline']/tr/td");

				Movie.Title = NODES[1].InnerText.Trim();
				Movie.Year = Convert.ToInt32(NODES[3].InnerText.Replace(Environment.NewLine, "").Replace(" ", "").Trim().Substring(0, 4));
				Movie.Director = NODES[9].InnerText.Trim();

				string[] genres = NODES[NODES.Count - 3].InnerText.Trim().Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);

				for (int i = 0; i < genres.Length; i++)
				{
					Genre obj = new Genre();
					obj.Name = genres[i];

					Movie.Genres.Add(obj);
				}
			}
			catch (Exception e) { }
			
			return Movie;
		}

		public Movie GetMovieInfo(string title)
		{
			try
			{
				Movie Movie = new Movie();

				string URL = "http://www.google.com/cse?cx=008177178803676006601:mrme5orikjy&cof=FORID:9&ie=ISO-8859-1&q=" + title;

				StreamReader sr = new StreamReader(Web.OpenRead(URL));
				string content = sr.ReadToEnd();

				sr.Close();
				sr.Dispose();

				Regex re = new Regex("http://www\\.filmaffinity\\.com/es/film(_?\\w*)*\\.html", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

				if (re.IsMatch(content))
				{
					string URLFILM = re.Matches(content)[0].Value.Trim().Replace("/es/", "/en/");

					sr = new StreamReader(new WebClient().OpenRead(URLFILM));
					string html = sr.ReadToEnd();

					Regex r2 = new Regex("http://pics\\.filmaffinity\\.com/(_?-?\\w*)*-large\\.jpg", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
					if (r2.IsMatch(html))
						Movie.Poster = r2.Matches(html)[0].Value; //Poster. No siempre funciona.
					else
						Movie.Poster = "http://hpneo.com/DoubleFeature/img/poster_default.jpg";

					HtmlAgilityPack.HtmlDocument HD = new HtmlAgilityPack.HtmlDocument();
					HD.LoadHtml(html);

					HtmlAgilityPack.HtmlNodeCollection NODES = HD.DocumentNode.SelectNodes("//table[@valign='baseline']/tr/td");

					if (NODES.Count > 0)
					{
						Movie.Title = NODES[1].InnerText.Trim();
						Movie.Year = Convert.ToInt32(NODES[3].InnerText.Replace(Environment.NewLine, "").Replace(" ", "").Trim().Substring(0, 4));
						Movie.Director = NODES[9].InnerText.Trim();

						string[] genres = NODES[NODES.Count - 3].InnerText.Trim().Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);

						for (int i = 0; i < genres.Length; i++)
						{
							Genre obj = new Genre();
							obj.Name = genres[i];

							Movie.Genres.Add(obj);
						}
					}
				}

				return Movie;
			}
			catch (Exception e)
			{
				//log
				return null;
			}
		}

		public List<Movie> GetMoviesSuggestions(string title)
		{
			List<Movie> Movies = new List<Movie>();
			try
			{
				string URL = "http://www.google.com/cse?cx=008177178803676006601:mrme5orikjy&cof=FORID:9&ie=ISO-8859-1&q=" + title;

				StreamReader sr = new StreamReader(Web.OpenRead(URL));
				string content = sr.ReadToEnd();

				sr.Close();
				sr.Dispose();

				Regex re = new Regex("http://www\\.filmaffinity\\.com/es/film(_?\\w*)*\\.html", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

				MatchCollection matches = re.Matches(content);

				if (matches.Count > 0)
				{
					for (int i = 0; i < matches.Count; i++)
					{
						Movie Movie = GetMovieInfoFromURL(matches[i].Value.Trim().Replace("/es/", "/en/"));
						if (Movie.Title.Trim() == "")
							continue;
						Movies.Add(Movie);
					}
				}
			}
			catch (Exception e)
			{
				//return null;
			}
			return Movies;
		}
	}
}